<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小额贷款 - 还款计划</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <nav class="navbar navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fas fa-money-bill-wave me-2"></i>小额贷款
            </a>
            <div>
                <a href="/loan-status" class="btn btn-outline-light me-2">我的贷款</a>
                <a href="#" class="btn btn-outline-light" onclick="logout()">退出</a>
            </div>
        </div>
    </nav>

    <div class="container mt-5">
        <h2 class="mb-4">还款计划</h2>
        <div id="loanInfo" class="card mb-4">
            <div class="card-body">
                <div class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
            </div>
        </div>
        
        <h3 class="mb-3">还款明细</h3>
        <div id="repaymentPlan" class="table-responsive">
            <div class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentLoanId = null;

        async function loadRepaymentPlan() {
            try {
                // 获取用户的贷款列表
                const response = await fetch('/api/loan-status');
                const data = await response.json();
                
                if (!data.success) {
                    alert(data.message);
                    if (data.message.includes('登录')) {
                        window.location.href = '/login';
                    }
                    return;
                }

                const approvedLoans = data.loans.filter(loan => loan.status === 'approved');
                
                if (approvedLoans.length === 0) {
                    document.getElementById('loanInfo').innerHTML = `
                        <div class="card-body text-center">
                            <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">暂无已通过的贷款</h5>
                            <a href="/loan-status" class="btn btn-primary mt-3">返回贷款列表</a>
                        </div>
                    `;
                    document.getElementById('repaymentPlan').innerHTML = '';
                    return;
                }

                // 默认显示第一个通过的贷款
                currentLoanId = approvedLoans[0].id;
                await loadRepaymentDetails(currentLoanId);
                
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('loanInfo').innerHTML = '<div class="text-center text-danger">加载失败，请刷新重试</div>';
            }
        }

        async function loadRepaymentDetails(loanId) {
            try {
                const response = await fetch(`/api/repayment/${loanId}`);
                const data = await response.json();
                
                if (data.success) {
                    displayLoanInfo(data.loan);
                    displayRepaymentPlan(data.repayment_plan);
                } else {
                    alert(data.message);
                }
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('repaymentPlan').innerHTML = '<div class="text-center text-danger">加载失败，请刷新重试</div>';
            }
        }

        function displayLoanInfo(loan) {
            document.getElementById('loanInfo').innerHTML = `
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h5 class="card-title">贷款详情</h5>
                            <p class="card-text">
                                <strong>贷款金额：</strong>¥${loan.amount}<br>
                                <strong>贷款期限：</strong>${loan.period}个月<br>
                                <strong>月利率：</strong>${(loan.monthly_rate * 100).toFixed(1)}%<br>
                                <strong>总利息：</strong>¥${loan.total_interest.toFixed(2)}
                            </p>
                        </div>
                        <div class="col-md-6">
                            <h5 class="card-title">还款信息</h5>
                            <p class="card-text">
                                <strong>总还款：</strong>¥${loan.total_amount.toFixed(2)}<br>
                                <strong>月供：</strong>¥${loan.monthly_payment.toFixed(2)}<br>
                                <strong>下次还款：</strong>${loan.next_payment_date ? new Date(loan.next_payment_date).toLocaleDateString() : '待确认'}
                            </p>
                        </div>
                    </div>
                </div>
            `;
        }

        function displayRepaymentPlan(plan) {
            document.getElementById('repaymentPlan').innerHTML = `
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>期数</th>
                            <th>还款日期</th>
                            <th>还款金额</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${plan.map(item => `
                            <tr>
                                <td>第${item.period}期</td>
                                <td>${item.payment_date}</td>
                                <td>¥${item.amount.toFixed(2)}</td>
                                <td>
                                    <span class="badge bg-${item.status === 'paid' ? 'success' : 'warning'}">
                                        ${item.status === 'paid' ? '已还款' : '待还款'}
                                    </span>
                                </td>
                                <td>
                                    ${item.status === 'pending' ? 
                                        `<button class="btn btn-primary btn-sm" onclick="repay(${item.period})">立即还款</button>` : 
                                        '<span class="text-success">已完成</span>'
                                    }
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        }

        function repay(period) {
            alert(`第${period}期还款功能演示：这里会跳转到支付页面`);
        }

        async function logout() {
            try {
                await fetch('/logout');
                window.location.href = '/';
            } catch (error) {
                window.location.href = '/';
            }
        }

        // 页面加载完成后获取还款计划
        document.addEventListener('DOMContentLoaded', loadRepaymentPlan);
    </script>
</body>
</html>